package com.efounder.service.util;


import android.util.Log;

import com.core.xml.StubObject;
import com.efounder.service.Registry;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class RegistryUtil {
    private static final String TAG = "RegistryUtil";
    public static final String ATTR_PARENT_ID = "_parentID";
    //解析fmt的工具类 在androidforwechatcomps库中

    public static void initRegistry(String fileName) {
        parseXml(fileName);
    }

    public static ReflectUtils getFmtFormatUil() {
        try {
            ReflectUtils fmtFormatUil = ReflectUtils.reflect("com.pansoft.xmlparse.MobileFormatUtil").method("getInstance");
            return fmtFormatUil;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param xmlPath
     * @return
     */
    private static void parseXml(String xmlPath) {
        File xmlFile = new File(xmlPath);
        if (xmlFile.exists()) {
            try {
                //首先得到：得到 DOM 解析器的工厂实例
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(new FileInputStream(xmlFile));
                Element rootElement = document.getDocumentElement();

                String id = rootElement.getAttribute("id");
                if ("mobile_fmt".equals(id)) {
                    //任务fmt 配置，反射相关类解析
                    try {
//                        Class mobileFormatUtilClass = Class.forName("com.pansoft.xmlparse.MobileFormatUtil");
//                        if (mobileFormatUtilClass != null) {
//                            //执行 getinstance
//                            Method m = mobileFormatUtilClass.getDeclaredMethod("getInstance", new Class[]{});
//                            Object object = m.invoke(new Class[]{}, new Object[]{});
//                            Method parseXMLMethod = mobileFormatUtilClass.getDeclaredMethod("parseXML", Element.class);
//                            parseXMLMethod.invoke(object, rootElement);
//                        }
                        getFmtFormatUil().method("parseXML", rootElement);
                    } catch (Exception e) {
                        Log.e(TAG, "反射MobileFormatUtil失败");
                    }
                    return;
                }

                parseRootElement(rootElement);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "----xml文件解析失败，文件不合法-->文件名:" + xmlFile.getAbsolutePath() + " 请使用notePad++检查您的文件----");
            }
        }
    }

    /**
     * 解析 fmt相关配置文件
     *
     * @param xmlPath
     * @return
     */
    public static Element parseFmtXml(String xmlPath) {
        File xmlFile = new File(xmlPath);
        if (xmlFile.exists()) {
            try {
                //首先得到：得到 DOM 解析器的工厂实例
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(new FileInputStream(xmlFile));
                Element rootElement = document.getDocumentElement();

                String id = rootElement.getAttribute("id");
                if ("mobile_fmt".equals(id)) {
                    return rootElement;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    private static void parseRootElement(Element rootElement) {
        NodeList nodeList = rootElement.getChildNodes();//一级节点，如：<menuRoot />
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                parseOneLevelElement((Element) node);
            }
        }
    }

    private static void parseOneLevelElement(Element oneLevelElement) {
        String oneLevelElementName = oneLevelElement.getNodeName();
        NodeList nodeList = oneLevelElement.getChildNodes();//二级节点：<node />
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                parseNodeElement(oneLevelElementName, (Element) node);
            }
        }
    }

    private static void parseNodeElement(String oneLevelElementName, Element nodeElement) {
        StubObject stub = new StubObject();
        NamedNodeMap attrs = nodeElement.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            stub.setString(attr.getNodeName(), attr.getNodeValue());
        }
        stub.setString(ATTR_PARENT_ID, oneLevelElementName);

        //注册
        Registry.regStubObjectList(oneLevelElementName, stub);
        String nodeID = nodeElement.getAttribute("id");
        if (nodeID == null || "".equals(nodeID)) {
            return;
        }
        Registry.regStubObject(nodeID, stub);

    }

}
